const puppeteer = require("puppeteer");
const logger = require("../lib/logger").logger;

class TaobBao {
  async set_cookie(cookies) {
    this.cookies = cookies;
  }

  async read_item_info(url) {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.setUserAgent(
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"
    );
    await page.goto(url);

    const cookies = this.cookies;
    // 设置cookie
    if (!cookies) {
      throw new Error("未设置cookie，无法读取数据");
    }
    await Promise.all(
      cookies.map(cookie => {
        return page.setCookie(cookie);
      })
    );
    await page.reload(); //设置完cookie需要重新刷新页面

    const g_config = await page.evaluate(() => window.g_config);
    const hub = await page.evaluate(() => window.Hub);
    // logger.info(JSON.stringify(g_config));
    // logger.info(JSON.stringify(hub));

    let price = g_config.sibRequest.data.price; // 默认显示原价格

    let sku = g_config.dynStock.sku; //sku key列表
    let originalPrice = g_config.originalPrice; // sku 原始价格
    let promoData = g_config.promotion.promoData; //sku 实际价格列表

    let itemInfo = {};
    itemInfo.itemId = g_config.itemId; //商品ID
    itemInfo.title = g_config.idata.item.title; //商品标题
    itemInfo.auctionImages = g_config.idata.item.auctionImages; //商品图片

    await page.waitForSelector("ul.J_TSaleProp>li");

    const skuImgList = await page.evaluate(() => {
      //这应该是在浏览器上执行的代码
      let elements = document.querySelectorAll("ul.J_TSaleProp>li");

      let data = [];
      for (const element of elements) {
        let skuId = element.getAttribute("data-value");
        let title = element.querySelector("span").innerText;
        let style = element.querySelector("a").getAttribute("style");
        let imgs = [];
        if (style && typeof style === "string") {
          imgs = style.match(/\/\/.*\.jpg/g);
        }
        let img = imgs ? imgs[0] : null;
        data.push({ skuId, title, img });
      }
      return data;
    });

    logger.info(skuImgList);

    for (const item of skuImgList) {
      let skuId = `;${item.skuId};`;
      let realPrice = promoData[skuId][0].price;
      item.realPrice = realPrice;
    }
    logger.info(skuImgList);

    itemInfo.sku=skuImgList;

    await page.waitForSelector("#J_DivItemDesc>p>img");
    const itemDescImgList = await page.$$eval(
      "#J_DivItemDesc>p>img",
      elements => {
        return elements.map(element => {
          if (element.getAttribute("data-ks-lazyload")) {
            return element.getAttribute("data-ks-lazyload");
          }
          return element.getAttribute("src");
        });
      }
    );
    itemInfo.descImgs = itemDescImgList;
    logger.info(itemDescImgList);

    await browser.close();
    return itemInfo;
  }
}

var taobao = new TaobBao();

module.exports = taobao;
